<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="communityLabel" placeholder="请输入小区/楼栋名称" clearable size="small"
            prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="communityOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="摄像头名称" prop="liftName" label-width="150px">
            <el-input v-model="queryParams.liftName" placeholder="请输入摄像头名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="楼栋uuid" prop="deptId">
          <el-input
            v-model="queryParams.deptId"
            placeholder="请输入楼栋uuid"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
          <!-- <el-form-item label="摄像头型号" prop="cameraAttribute" label-width="120px">
            <el-input v-model="queryParams.cameraAttribute" placeholder="请输入摄像头型号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="摄像头状态" prop="cameraStatus" label-width="120px">
            <el-select v-model="queryParams.cameraStatus" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['camera:camera:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['camera:camera:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['camera:camera:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['camera:camera:export']">导出</el-button>
          </el-col>
          <!-- <el-col :span="1.5"> -->
          <!-- {{ '锂电池识别算法：'}}
            <el-switch v-model="arithmeticObj.algorithmStatus" :active-value='1' :inactive-value='0' @change="toggleAlgorithm">
            </el-switch> -->
          <!-- <el-button type="primary" size="mini" style="margin-left: 100px" v-if="true" @click="toggleAlgorithm">{{(arithmeticObj.algorithmStatus==0?'开启':'关闭')+'锂电池识别算法'}}</el-button> -->
          <!-- <el-button type="primary" size="mini" style="margin-left: 100px" v-else @click="toggleAlgorithm">开启锂电池识别算法</el-button> -->
          <!-- </el-col> -->

          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="cameraList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="摄像头名称" align="center" prop="liftName" />
          <!-- <el-table-column label="摄像头型号" align="center" prop="cameraAttribute" /> -->
          <el-table-column label="摄像头状态" align="center" prop="cameraStatus">
            <template slot-scope="scope">
              <el-tag :type="scope.row.cameraStatus == 0 ? 'success' : 'danger'">{{ scope.row.cameraStatus == 0 ? "开启" :
                "关闭" }}</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column label="算法状态" align="center">
            <template slot-scope="{ row }">
              {{ row.algorithmStatus == 0 ? "开启" : "关闭" }}
            </template>
          </el-table-column> -->
          <el-table-column label="摄像头ip" align="center" prop="cameraIp"></el-table-column>
          <el-table-column label="摄像头端口" align="center" prop="cameraPort"></el-table-column>
          <el-table-column label="RTSP端口" align="center" prop="cameraRtspPort"></el-table-column>
          <el-table-column label="摄像头登录名" align="center" prop="cameraName"></el-table-column>
          <el-table-column label="摄像头协议" align="center" prop="protocol"></el-table-column>
          <el-table-column label="摄像头品牌" align="center" prop="brand"></el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['camera:camera:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['camera:camera:remove']">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-view" @click="showPreview(scope.row)">预览</el-button>
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="restart(scope.row)"
                >重启</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
      <!-- <el-col :span="20" :xs="24" v-else> -->

      <!-- <div class="shexiangtou" id="divPlugin"></div> -->
      <!-- <div class="cell">
          <div class="cell-tool">
            <div class="bk-button-group">
              <button
                @click="cellCountFn(item.number)"
                v-for="(item, index) in iconArr"
                :key="index"
              >
                {{ item.number }}
              </button>
            </div>
          </div>
          <div class="player">
            <div
              :class="cellClass(index2)"
              v-for="(i, index2) in cellCountArr"
              :key="index2"
            >
              <playVideo :str1="index2 + 1"></playVideo>
            </div>
          </div>
        </div> -->
      <!-- </el-col> -->
    </el-row>

    <!-- 添加或修改电梯/摄像头对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="小区/楼栋" prop="deptId">
          <treeselect v-model="form.deptId" :options="communityOptions" :show-count="true" placeholder="小区/楼栋"
            @input="riskPersonDeptChangeValue" />
        </el-form-item>
        <el-form-item label="摄像头名称" prop="liftName" label-width="110px">
          <el-input v-model="form.liftName" placeholder="请输入摄像头名称" />
        </el-form-item>
        <el-form-item label="登录账号" prop="cameraName" label-width="110px">
          <el-input v-model="form.cameraName" placeholder="请输入摄像头登录名" />
        </el-form-item>
        <el-form-item label="登录密码" prop="cameraPassword" label-width="110px">
          <el-input v-model="form.cameraPassword" placeholder="请输入登录密码" show-password />
        </el-form-item>
        <el-form-item label="摄像头Ip" prop="cameraIp" label-width="110px">
          <el-input v-model="form.cameraIp" placeholder="请输入摄像头Ip" />
        </el-form-item>
        <el-form-item label="RTSP端口" prop="cameraRtspPort" label-width="110px">
          <el-input v-model="form.cameraRtspPort" placeholder="请输入RTSP端口" />
        </el-form-item>
        <el-form-item label="摄像头端口" prop="cameraPort" label-width="110px">
          <el-input v-model="form.cameraPort" placeholder="请输入摄像头端口" />
        </el-form-item>
        <el-form-item label="摄像头协议" prop="protocol" label-width="110px">
          <el-input v-model="form.protocol" placeholder="请输入摄像头协议" />
        </el-form-item>
        <el-form-item label="摄像头品牌" prop="brand" label-width="110px">
          <el-input v-model="form.brand" placeholder="请输入摄像头品牌" />
        </el-form-item>

        <!-- <el-form-item label="楼栋uuid" prop="deptId">
            <el-input v-model="form.deptId" placeholder="请输入楼栋uuid" />
          </el-form-item> -->
        <!-- <el-form-item label="摄像头型号" prop="cameraAttribute" label-width="100px">
          <el-input v-model="form.cameraAttribute" placeholder="请输入摄像头型号" />
        </el-form-item> -->

        <!-- <el-form-item label="摄像头状态" prop="cameraStatus" label-width="110px">
          <el-select v-model="form.cameraStatus" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="rtsp流" prop="cameraRtsp">
          <el-input v-model="form.cameraRtsp" placeholder="请输入rtsp流" />
        </el-form-item> -->
        <!-- <el-form-item label="删除标志(0:未删除,1:已删除)" prop="del">
            <el-input v-model="form.del" placeholder="请输入删除标志(0:未删除,1:已删除)" />
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="监控画面" :visible.sync="formSwitch" width="1080px" append-to-body @close="closeCamera">
      <div class="cameraDiv" v-if="currentCameraInfo.length > 0">
        <!-- <camera v-for="v in cameraList" :hkvInfo="v" :key="v.id"></camera> -->
        <cameraBox :cameraList="currentCameraInfo" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCamera,
  getCamera,
  delCamera,
  addCamera,
  updateCamera,
  getCommunityTree,
  getCameraByCommunityId,
  algorithm,
} from "@/api/camera/camera";
import { deptTreeSelect } from "@/api/system/user";
import { getCameraOnline } from "@/api/camera/camera.js"
import {
  changeLithiumBattery,
  getLithiumBatteryStatus,
} from "@/api/camera/arithmetic.js";
// import { clickStopRealPlay } from "./webVideo";
import { WebVideo } from "./webVideo.js";
import camera from "./camera.vue";
import cameraBox from "./cameraDiv.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "cameraIndex",
  components: {
    Treeselect,
    camera,
    cameraBox,
  },

  data() {
    var validateDeptId = (rule, value, callback) => {
      let obj = this.findItemById(this.communityOptions[0], Number(value));
      if (obj.levelRank && obj.levelRank == 4) {
        callback();
      } else {
        callback(new Error("需要选择楼栋层级"));
      }
    };
    return {
      isAlgorithmEnabled: true,
      hkvInfo: {
        ip123: "192.168.1.89",
        username: "admin",
        password: "lanbu@2024",
      },
      currentCameraInfo: [],
      WebVideo: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 是否显示表格内容
      formSwitch: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电梯/摄像头表格数据
      cameraList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 小区楼栋树数据
      communityOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      communityLabel: "",
      options: [
        {
          value: "0",
          label: "开启",
        },
        {
          value: "1",
          label: "关闭",
        },
      ],
      arithmeticList: [],
      arithmeticObj: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liftName: null,
        deptId: null,
        // cameraAttribute: null,
        cameraStatus: null,
        cameraRtsp: null,
        del: null,
        cameraPort: 80,
        cameraPassword: null,
        cameraName: "",
        cameraIP: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "请选择小区/楼栋", trigger: "change" },
          // { validator: validateDeptId, trigger: "change" },//解释：验证deptId是否为楼栋层级
        ],
        cameraName: [
          { required: true, message: "摄像头登录名不能为空", trigger: "blur" },
        ],
        cameraPassword: [
          { required: true, message: "登录密码不能为空", trigger: "blur" },
        ],
        cameraPort: [
          { required: true, message: "摄像头端口不能为空", trigger: "blur" },
        ],
        liftName: [
          { required: true, message: "摄像头名称不能为空", trigger: "blur" },
        ],
        protocol: [
          { required: true, message: "摄像头协议不能为空", trigger: "blur" },
        ],
        brand: [
          { required: true, message: "摄像头品牌不能为空", trigger: "blur" },
        ],
        //   deptId: [
        //     { required: true, message: "楼栋uuid不能为空", trigger: "blur" }
        //   ],
        cameraStatus: [
          { required: true, message: "摄像头状态不能为空", trigger: "change" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],

        // cameraAttribute: [
        //   { required: true, message: "摄像头型号不能为空", trigger: "blur" },
        // ],
        cameraIp: [
          { required: true, message: "摄像头Ip不能为空", trigger: "blur" },
        ],
        cameraRtspPort: [
          { required: true, message: "RTSP端口不能为空", trigger: "blur" },
        ],
        // cameraRtsp: [
        //   { required: true, message: "rtsp流不能为空", trigger: "blur" },
        // ],

      },
      hkvInfo: {
        ip123: "192.168.1.89",
        username: "admin",
        password: "lanbu@2024",
      },
    };
  },

  created() {
    this.webVideo = new WebVideo();
    this.getList();
    this.getCommunityTreeData();
    // this.getArithmetic();
    // this.clickStopRealPlay();
  },
  // mounted() {
  //   this.webVideo = new WebVideo();
  //   this.$nextTick(() => {
  //     // this.webVideo.init("192.168.2.89", "admin", "lanbu@2024", "divPlugin");
  //     this.webVideo.init("divPlugin");
  //     // window.setTimeout(() => {
  //     //   this.webVideo.clickLogin();
  //     // }, 1000);
  //   });
  // },
  // beforeDestroy() {
  //   this.webVideo.clickStopRealPlay();
  //   this.webVideo.clickLogout();
  //   this.webVideo.close_JSVideoPlugin();
  // },
  watch: {
    // 根据名称筛选小区树
    communityLabel(val) {
      this.$refs.tree.filter(val);
    },

    // formSwitch: {
    //   handler(val) {
    //     if (val == false) {
    //       this.$nextTick(() => {
    //         // this.webVideo.init("192.168.2.89", "admin", "lanbu@2024", "divPlugin");
    //         this.webVideo.init("divPlugin");
    //         // window.setTimeout(() => {
    //         //   this.webVideo.clickLogin();
    //         // }, 1000);
    //       });
    //       if (this.cameraList.length == 0) {
    //         listCamera(this.queryParams).then((response) => {
    //           this.cameraList = response.rows;
    //           this.cameraList.forEach((v, i) => {
    //             // this.clickLogin(v, i);
    //           });
    //         });
    //       } else {
    //         this.cameraList.forEach((v, i) => {
    //           this.clickLogin(v, i);
    //           console.log(3);
    //         });
    //       }
    //     } else {
    //       // this.webVideo.clickStopRealPlay();
    //       // this.webVideo.clickLogout();
    //       // this.webVideo.close_JSVideoPlugin();
    //     }
    //   },
    //   immediate: true,
    // },
  },

  methods: {
    riskPersonDeptChangeValue() {
      //form是表单名 riskPersonDept是prop名
      this.$refs["form"].validateField("deptId");
    },

    findItemById(tree, id) {
      // 如果当前节点的ID匹配，直接返回当前节点
      if (tree.id === id) {
        return tree;
      }
      if (!tree.children) {
        return null;
      }
      for (const child of tree.children) {
        const result = this.findItemById(child, id);
        if (result) {
          return result;
        }
      }
      // 如果未找到匹配的项，返回null
      return null;
      // 否则，递归地在子节点中查找
      // for (const child of tree.children) {
      //   const result = this.findItemById(child, id);
      //   if (result) {
      //     return result;
      //   } else {
      //     return null;

      //   }
      // }
      // 如果未找到匹配的项，返回null
    },
    //查询锂电池识别算法的运行状态
    // getArithmetic () {
    //   getLithiumBatteryStatus().then(res => {
    //     this.arithmeticObj = res.data;
    //     console.log(1, this.arithmeticObj);
    //     // this.arithmeticList = res.data;
    //     // if (this.arithmeticList.algorithmStatus == 1) {
    //     //   console.log(this.arithmeticList, 11111);
    //     //   this.isAlgorithmEnabled = true;
    //     // }
    //   })
    // },
    // 点击开启/关闭算法
    // toggleAlgorithm (val) {
    //   // if (this.isAlgorithmEnabled) {
    //   //   stopLithiumBattery().then(() => {
    //   //     this.isAlgorithmEnabled = false;
    //   //     this.$modal.msgSuccess("锂电池识别算法已关闭");
    //   //   })
    //   // } else {
    //   //   startLithiumBattery().then(() => {
    //   //     this.$modal.msgSuccess("锂电池识别算法已开启");
    //   //     this.isAlgorithmEnabled = true;
    //   //   })
    //   // }
    //   // let data = this.arithmeticObj
    //   // if (this.arithmeticObj.algorithmStatus == 0) {
    //   //   this.arithmeticObj.algorithmStatus = 1
    //   // } else if (this.arithmeticObj.algorithmStatus == 1) {
    //   //   this.arithmeticObj.algorithmStatus = 0
    //   // }
    //   // console.log('this.arithmeticObj', val);
    //   // this.arithmeticObj.algorithmStatus = val
    //   changeLithiumBattery(this.arithmeticObj).then(res => {
    //     console.log(res);
    //     this.$modal.msgSuccess("操作成功");
    //   })
    // },
    closeCamera() {
      this.webVideo.clickStopRealPlay(0);
      this.webVideo.clickLogout(this.currentCameraInfo[0].cameraIp);
      window.setTimeout(() => {
        this.webVideo.close_JSVideoPlugin();
        this.currentCameraInfo = [];
      }, 100);
    },
    // restart(row) {
    //   getCamera(row.id).then((res) => {
    //     let data = res.data;
    //     const loading = this.$loading({
    //       lock: true,
    //       text: "重启中",
    //       spinner: "el-icon-loading",
    //       background: "rgba(0, 0, 0, 0.7)",
    //     });
    //     algorithm(data).then((res1) => {
    //       setTimeout(() => {
    //         this.$modal.msgSuccess(res1.msg);
    //         this.getList();
    //         loading.close();
    //       }, 6000);
    //     });
    //   });
    // },
    // showPreview(row) {
    //   this.checkCameraOnline(row);
    // },

    // 监测摄像头是否在线
    showPreview(row) {
      this.loading = true;
      getCameraOnline(row.cameraIp, row.cameraPort).then((res) => {
        if (res.code == 200) {
          this.currentCameraInfo = [row];
          this.formSwitch = true; // 显示预览
        }
      }).finally(() => {
        this.loading = false;
      })
    },

    clickLogin(obj) {
      if (obj.cameraIp == "192.168.1.64") {
        this.webVideo.clickLogin(
          obj.cameraIp,
          obj.cameraName,
          obj.cameraPassword
        );
      }
    },
    /** 查询电梯/摄像头列表 */
    getList() {
      this.loading = true;
      listCamera(this.queryParams).then((response) => {
        this.cameraList = response.rows;
        this.cameraList = this.cameraList.map((item) => {
          item.cameraId =
            "cameraId" +
            item.cameraIp.split(".")[2] +
            item.cameraIp.split(".")[3];
          return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取小区楼栋数结构
    getCommunityTreeData() {
      deptTreeSelect().then((response) => {
        this.communityOptions = response.data;
        // let tree = response.data[0];
        // this.addLevels(tree);
        // console.log(123, tree, 11111);
        // console.log(123, this.communityOptions, 11111);
      });
    },
    addLevels(tree, level = 0) {
      tree.level = level; // 将当前节点的层级添加到节点中

      // 检查当前节点是否有子节点
      if (tree.children && tree.children.length > 0) {
        // 递归遍历子节点并为它们添加层级字段
        for (const child of tree.children) {
          this.addLevels(child, level + 1);
        }
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(node) {
      // 在这里调用 getCameraByCommunityId 方法，传递点击的节点的 ID
      const communityId = node.id;
      getCameraByCommunityId(communityId).then((response) => {
        // 处理返回的数据，例如更新表格数据
        this.cameraList = response.data;
        // this.total = response.total;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        liftName: null,
        deptId: null,
        // cameraAttribute: null,
        cameraStatus: null,
        cameraRtsp: null,
        createTime: null,
        updateTime: null,
        del: null,
        cameraPort: 80,
        cameraPassword: null,
        cameraName: "",
        cameraIp: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加摄像头";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCamera(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改摄像头";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCamera(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCamera(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除电梯/摄像头编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCamera(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "camera/camera/export",
        {
          ...this.queryParams,
        },
        `camera_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.shexiangtou {
  height: 700px;
  width: 100%;
  // background-color: yellow;
}

.cameraDiv {
  height: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
